<template>
	<div>
		<div class="banner">
			<image :src="banner" mode="widthFix"></image>
		</div>
		<view class="container">
			<div class="items">
				<div class="time"><span><u-icon name="clock" color="#d9232f" size="24"></u-icon></span>{{userInfo.time}} s</div>
				<div class="answerBtn" v-if="userInfo.status == '已提交'" @click="page = -1; paimingList = []; getPaiming()"><span><u-icon name="eye" color="#d9232f" size="24"></u-icon></span>查看排名</div>
				<div class="item" v-for="(item,index) in list" :key="index">
					<h3> {{index + 1}}、 {{ item.title }}</h3>
					
					<ul>
						<li v-for="(li,j) in item.options" :key="j" @click="changeOption(index,j)" :class="{'cur' :item.selects.includes(j.toString()),'correct': item.correct.includes(j.toString()) && userInfo.status =='已提交'}"> <div class="circle"></div> {{ li }}</li>
					</ul>
				</div>
				
				<div class="subBox" v-if="userInfo.status != '已提交'">
					<u-button type="error" text="提交" @click="subInfo()"></u-button>
				</div>
			</div>
		</view>
		
		<u-popup :show="showpop" @close="showpop= false" mode="center" :safeAreaInsetBottom="false">
			<div class="popcontent">
				<div class="cell">
					<div class="label">请选择头像</div>
					<div class="w70">
						<div class="ava">
							<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"style="padding: 0; margin: 0;">
								<image v-if="userInfo.avatarUrl" class="avatar" :src="userInfo.avatarUrl" mode="widthFix"></image>
								<image v-else class="avatar" src="https://www.baixuemianshi.com/zhuanti/images/ava.png" mode="widthFix"></image>
							</button>
						</div>
					</div>
				</div>
				<div class="cell">
					<div class="label">请输入昵称</div>
					<div class="w70">
						<div class="nicknameBox">
							<input type="nickname" v-model="userInfo.nickname" @blur="blurname" placeholder="请输入昵称" />
						</div>
					</div>
				</div>
				<div class="">
					<u-button type="error" text="更新信息" @click="showpop = false"></u-button>
				</div>
			</div>
		</u-popup>
		
		
		<div class="popup" v-if="showPrivacy">
			<div class="popcontent">
				<view class="privacyTit">用户隐私保护提示</view>
				<div class="poptext">感谢您的使用，在使用本小程序前，应当阅读并同意<text
						@click="handleOpenPrivacyContract">《用户隐私保护指引》</text>。当您点击同意并开始使用程序服务时，即表示您已理解并同意该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法进入小程序。
				</div>
				<div class="btns">
					<div class="btn"><u-button shape="circle" @tap="showPrivacy = false">不同意并退出</u-button></div>
					<div class="btn"><u-button type="error" shape="circle" id="agree-btn"
							open-type="agreePrivacyAuthorization"
							@click="handleAgreePrivacyAuthorization">同意并继续</u-button></div>
				</div>
			</div>
		</div>
		
		<u-popup :show="showpaiming" @close="showpaiming= false" mode="center" :safeAreaInsetBottom="false">
			<div class="popcontent">
				<div class="cell thead">
					<div class="num">排名</div>
					<div class="ava">
						头像
					</div>
					<div class="nickname">昵称</div>
					<div class="score">得分</div>
					<div class="alltime">用时</div>
				</div>
				<div class="overBox">
					<div class="cell" v-for="(item,index) in paimingList" :key="index">
						<div class="num">{{index + 1}}</div>
						<div class="ava">
							<image :src="item.avatarUrl" mode="widthFix"></image>
						</div>
						<div class="nickname">{{ item.nickname }}</div>
						<div class="score">{{ item.score }}</div>
						<div class="alltime">{{ item.time }}s</div>
					</div>
					<div class="loadMore" @click="getPaiming()">加载更多+</div>
				</div>
				
			</div>
		</u-popup>
		
		
	</div>

</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		name: 'headcomd',
		data() {
			return {
				banner: "https://www.baixuemianshi.com/zhuanti/images/banner_tf.jpg?" + new Date,
				list: [{
						"title": "以下哪个是准确的集团品牌名",
						"options": ["雪恒教育", "恒雪教育", "雪睿教育", "睿雪教育"],
						"correct": "0",
						"selects": ""
					},
					{
						"title": "机构创始人",
						"options": ["小白老师", "白雪老师", "雪白老师", "雪恒老师"],
						"correct": "1",
						"selects": ""
					},
					{
						"title": "以下选项哪个品牌为官方白雪面试？",
						"options": ["恒雪教育-白雪面试", "雪恒教育-白雪面试", "白雪教育", "白雪公考"],
						"correct": "1",
						"selects": ""
					},
					{
						"title": "以下哪个是品牌宣传语",
						"options": ["十二年专注，只做公考", "十二年专注，只做面试", "十二年专注，只做公考面试", "十二年专注，只做面试公考"],
						"correct": "1",
						"selects": ""
					},
					{
						"title": "口号",
						"options": ["攻必克 守必赢 白雪面试一定行", "攻必克 守必赢 雪恒面试一定行", "攻必克 守必赢 雪恒白雪一定行", "攻必克 守必赢 雪恒教育一定行"],
						"correct": "2",
						"selects": ""
					},
					{
						"title": "想要报名白雪面试需要认准以下哪个条件？（多选）",
						"options": ["【白雪教育】", "【雪恒教育】", "【恒雪教育】", "【白雪老师】"],
						"correct": "13",
						"selects": ""
					}
				],
				openid: "",
				userInfo: {
					_id: "",
					phone: "",
					answerList: [],
					nickname: "",
					avatarUrl: "",
					time: 0,
					status: ""
				},
				showpop:false,
				showPrivacy: false,
				setTime: null,
				
				showpaiming: false,
				paimingList: [],
				page: -1,
				stopTime: false,
				
				
				avaLink: "",
				
			};
		},
		onShareAppMessage(options) {
			
			var shareObj = {
			    title: "雪恒白雪-真假大鉴别",    // 默认是小程序的名称(可以写slogan等)
			    path: '/pages/huodong/bxms_tf/index',    // 默认是当前页面，必须是以‘/'开头的完整路径
			    imageUrl: 'https://www.baixuemianshi.com/zhuanti/images/share.jpg',   //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
			    success: function(res){
			      // 转发成功之后的回调
			      if(res.errMsg == 'shareAppMessage:ok'){
			      }
			    }
			}
			return shareObj;
		},
		onShareTimeline(res) {
			return {
				title: '雪恒白雪-真假大鉴别',
				path: '/pages/huodong/bxms_tf/index',
				imageUrl: 'https://www.baixuemianshi.com/zhuanti/images/logo_squer.jpg'
			}
		},
		onLoad(options) {
			if (wx.getPrivacySetting) {
				wx.getPrivacySetting({
					success: res => {
						if (res.needAuthorization) {
							// 需要弹出隐私协议
							this.showPrivacy = true
						} else {
							// 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
							// wx.getUserProfile()
							// wx.chooseMedia()
							// wx.getClipboardData()
							// wx.startRecord()
						}
					},
					fail: () => {},
					complete: () => {}
				})
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
		},
		mounted() {
			let that = this
			
		},
		watch: {
			userphone(val){
				if(this.userphone){
					this.getUserDetail()
				}
			}
		},
		created() {
			this.getopenid()
		},
		methods: {
			getopenid() {
				let that = this
				wx.cloud.callFunction({
					name: 'getopenid',
					data: {},
					complete: res => {
						wx.setStorageSync("useropenid", res.result.openid)
						that.openid = res.result.openid
						that.getAnswer()
						that.getUserDetail()
					}
				})
			},
			getUserDetail(){
				let that = this
				db.collection('all_user').where({
					_openid: that.openid
				}).get({
					success: res => {
						console.log(res)
						if (res.data.length > 0) {
							that.userInfo._id = res.data[0]._id
							that.userInfo.phone = res.data[0].phone
							that.userInfo.nickname = res.data[0].nickname
							that.userInfo.avatarUrl = res.data[0].avatarUrl
							that.LogSetPhone(that.userInfo.phone)
						}
					}
				})
			},
			getAnswer(){
				let that = this
				db.collection('bxms_tf').where({_openid: that.openid}).get({
					success: res => {
						if(res.data.length > 0){
							that.userInfo.answerList = res.data[0].answerList
							that.userInfo.time = res.data[0].time
							that.userInfo.status = res.data[0].status
							that.filterAnswerList(res.data[0].answerList)
						}
						if(that.userInfo.time > 0){
							that.getPaiming()
						}
					}
				})
			},
			filterAnswerList(answers){
				let that = this
				
				answers.map((item,index) => {
					that.list[index].selects = item
				}) 
			},
			changeOption(index,j){
				let that = this
				if(this.userInfo.status == "已提交"){
					 uni.showToast({
					 	icon:"error",
						title:"不能重复答题"
					 })
					 return 
				}
				if(that.userInfo.time == 0 || that.stopTime){
					that.setTime = setInterval(function(){
						that.userInfo.time = Math.round(parseFloat(that.userInfo.time + 0.1)*100)/100
					},100)
				}
				that.stopTime = false
				if(this.list[index].correct.length <= 1){
					this.list[index].selects = j.toString()
				}else{
					let selects = this.list[index].selects.split("")
					if(selects.includes(j.toString())){
						selects = selects.filter(item => item != j)
					}else{
						selects.push(j.toString())
					}
					this.list[index].selects = selects.sort().join('')
					
					let l = this.list.map(item => item.selects)
					this.userInfo.answerList = l
				}
			},
			subInfo(){
				let that = this
				clearInterval(that.setTime)
				that.stopTime = true
				if(!that.userInfo.phone){
					uni.showToast({
						icon:"error",
						title:"请先登录"
					})
					uni.navigateTo({
						url:"../../my/login?navTlt=真假白雪面试"
					})
					return 
				}
				if(!that.userInfo.nickname || !that.userInfo.avatarUrl){
					uni.showToast({
						icon:"error",
						title:"请授权头像&昵称"
					})
					that.showpop = true
					return
				}
				
				let f = that.list.filter(item => item.selects == "")
				if(f.length > 0){
					uni.showToast({
						icon:"error",
						title:"题目未选完"
					})
					return
				}
				
				db.collection('bxms_tf').add({
					data: {
						phone: that.userInfo.phone,
						answerList: that.userInfo.answerList,
						nickname: that.userInfo.nickname,
						avatarUrl: that.userInfo.avatarUrl,
						time: that.userInfo.time,
						status: "已提交",
						score: that.getScore()
					},
					success: res => {
						uni.showToast({
							icon:"success",
							title:"提交成功！"
						})
						that.getAnswer()
					}
				})
			},
			getScore(){
				let score = 0
				this.list.map(item => {
					if(item.correct == item.selects){
						score += 1
					}
				})
				return score
			},
			getPaiming(){
				let that = this
				that.page += 1
				db.collection('bxms_tf').where({status: "已提交"}).orderBy('score','desc').orderBy('time','asc').skip(10 * that.page).limit(10).get({
					success: res =>{
						
						if(res.data.length > 0){
							that.paimingList = that.paimingList.concat(res.data)
							that.showpaiming = true
						}else{
							uni.showToast({
								icon:'error',
								title:'没有更多啦~'
							})
						}
					}
				})
			},
			onChooseAvatar(e) {
				let that = this
				const {
					avatarUrl
				} = e.detail
				uni.uploadFile({
					url: "https://www.baixuemianshi.com/zhuanti/upload_img/xcx2.php",
					filePath: e.detail.avatarUrl,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: res => {
						let status = JSON.parse(res.data) 
						if(status.status == 'success'){
							let link = 'https://www.baixuemianshi.com/zhuanti/upload_img/upload/' + status.data
							that.uploadAva(link)
						}else{
							uni.showToast({
								icon:"error",
								title:"上传失败"
							})
						}  
					}
				})
			},
			uploadAva(link) {
				let that = this
				
				db.collection('all_user').doc(that.userInfo._id).update({
					data: {
						avatarUrl: link
					},
					success: res => {
						that.getUserDetail()
					}
				})
			},
			blurname(e) {
				let that = this
				db.collection('all_user').doc(that.userInfo._id).update({
					data: {
						nickname: e.detail.value
					},
					success: res => {
						that.getUserDetail()
					}
				})
			},
			handleAgreePrivacyAuthorization() {
				this.showPrivacy = false
			},
			handleOpenPrivacyContract() {
				// 打开隐私协议页面
				wx.openPrivacyContract({
					success: () => {}, // 打开成功
					fail: () => {}, // 打开失败
					complete: () => {}
				})
			},

		}
	};
</script>

<style>
	@import url("./index.css");
</style>